<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\model\questionnaireModel;
use think\facade\Request;
use think\facade\Validate;
use think\facade\View;

class questionnaire
{
    public function index()
    {
        $questionList = questionnaireModel::select();
        View::assign('questionList',$questionList);
        return View::fetch('questionnaire/index');
    }

    public function edit()
    {
        $question_id = Request::param('question_id');
        $validate = Validate::rule([
            'question_id|问卷id' => 'require|between:1,'.PHP_INT_MAX,
        ]);

        if(!$validate->check(['question_id'=>$question_id])){
            echo $validate->getError();
            exit();
        }
        $questionList = questionnaireModel::where('question_id','=',$question_id)->find();
        View::assign('questionList',$questionList);
        return View::fetch('questionnaire/edit');
    }

    public function editSave()
    {
        $params = Request::param();
        $validate = Validate::rule([
            'question_id|问卷id' => 'require|between:1,'.PHP_INT_MAX,
            'title|问卷主题' => 'require',
            'explain|问卷说明' => 'require',
            'ques_one|选项1' => 'require',
            'ques_two|选项2' => 'require',
            'ques_three|选项3' => 'require',
            'ques_four|选项4' => 'require',
            'ques_five|选项5' => 'require',
        ]);

        if(!$validate->check($params)){
            echo $validate->getError();
            exit();
        }

        $params["update_time"] = time();

        $result = questionnaireModel::update($params);

        if ($result) {
            echo "<script>alert('编辑成功');</script>";
            echo "<script>location.href='/index.php?s=admin/questionnaire/index'</script>";
        } else {
            echo "<script>alert('编辑失败,请联系管理员：1292888678@qq.com');</script>";
        }
    }
    public function delete()
    {
        $question_id = Request::param('question_id');
        $validate = Validate::rule([
            'question_id|问卷id' => 'require|between:1,'.PHP_INT_MAX,
        ]);

        if(!$validate->check(['question_id'=>$question_id])){
            echo $validate->getError();
            exit();
        }
        $result = questionnaireModel::destroy($question_id);

        if ($result) {
            echo "<script>alert('删除成功');</script>";
            echo "<script>location.href='/index.php?s=admin/questionnaire/index'</script>";
        } else {
            echo "<script>alert('删除失败,请联系管理员：1292888678@qq.com');</script>";
        }
    }
}
